package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"novel_website_db/cache"
	"novel_website_db/models"
	"path/filepath"
	"strings"
)

type NovelController struct {
	beego.Controller
}

func (c *NovelController) Add() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "请选择要上传的图片",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	defer file.Close()
	if header.Size > 3*1024*1024 {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "上传的图片大小不可超过3MB",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	etx := map[string]bool{
		".png":  true,
		".jpg":  true,
		".jpeg": true,
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	if etx[suffix] == false {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "上传的图片格式只能是JPG、PNG、JPEG格式",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	path := "static/img/" + header.Filename
	c.SaveToFile("img", path)
	name := c.GetString("name")
	author := c.GetString("author")
	types := c.GetString("types")
	if name == "" || author == "" || types == "" {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "要添加的小说信息不可为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var n models.Novel
	n.Name = name
	n.Author = author
	n.Types = types
	n.Img = "http://127.0.0.1:8080/" + path
	err = n.Add()
	if err != nil {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "发布失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	novels, _ := n.GetList()
	jsonData, _ := json.Marshal(novels)
	cache.Rdb.Set(cache.Ctx, "novel", jsonData, 0)
	c.Data["json"] = Response{
		Code: 200,
		Msg:  "发布成功",
		Data: nil,
	}
	c.ServeJSON()
	return
}
